package com.work.leecode.array.easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数元素---169
 */
public class Lc169 {
    public static void main(String[] args) {
        int[] nums = {2, 2, 1, 1, 1, 2, 2, 1, 1};
        System.out.println(majorityElement(nums));
        System.out.println(majorityElement2(nums));
    }

    //方法一：哈希表方式
    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int maxKey = 0;
        int maxCount = 0;
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, (map.get(num) + 1));
                maxCount = maxCount > map.get(num) ? maxCount : map.get(num);
            } else {
                map.put(num, 1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == maxCount) {
                maxKey = entry.getKey();
            }
        }
        return maxKey;
    }

    //方法二：规律法---如果将数组 nums 中的所有元素按照单调递增或单调递减的顺序排序，那么下标为nums[n/2]一定是众数
    public static int majorityElement2(int[] nums) {
        Arrays.sort(nums);

        return nums[nums.length / 2];
    }
}
